package com.wwwarehouse.taskcenter.fragment.job_point.step4;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.fragment.CommonBasePagerFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.TaskPointChooseRelativethingBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.eventbus_event.TaskPointCardEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @创建者 chenchao.
 * @创建时间 2017/10/25 18:53
 * @描述 ${TODO}
 */

public class ChooseConnectObjectFragment4 extends CommonBasePagerFragment implements View.OnClickListener {

    private Button mBtSave;
    public static final int REQUEST_1 = 1003,REQUEST_CODE = 10004;
    private ArrayList<TaskPointChooseRelativethingBean.ListBean> listBean;

    private Map<String,TaskPointChooseRelativethingBean.ListBean> listBeanMap = new HashMap<>();
    private long jobPointUkid;
    private String warehouseUkid;

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseConnectObjectFragment4) {
            mActivity.setTitle("" + getString(R.string.new_task_step6_add));
        }
    }

    @Override
    public void requestDatas() {
        super.requestDatas();

        try {
            jobPointUkid = Long.parseLong(getArguments().getString("jobPointUkid"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        warehouseUkid = getArguments().getString("warehouseUkid");

        showConfirmButton();
        setConfirmBtnText("" + getString(R.string.new_task_save));
        mBtSave = (Button) getConfirmBtn();
        mBtSave.setOnClickListener(this);
        requestHttp();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDownPull() {
    }



    private void initPager() {
        Bundle budle = new Bundle();
        try {
            setData(listBean.size(), 10, "com/wwwarehouse/taskcenter/fragment/job_point/step4/ChooseConnectObjectDetailFragment", budle, listBean);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.showErrLog("error:"+e.getMessage());
        }
    }


    @Override
    public void onRefreshListener() {
        requestHttp();
    }

    @Override
    public void onLoadSuccess(String s, int i) {
        if (REQUEST_1 == i) {
            listBean = (ArrayList<TaskPointChooseRelativethingBean.ListBean>) JSON.parseArray(s,TaskPointChooseRelativethingBean.ListBean.class);
            initPager();
        }
    }

    @Override
    public void onLoadError(String s) {

    }

    /**
     *  查询类目
     */
    private void requestHttp() {
        Map<String, Object> map = new HashMap<>();
        map.put("warehouseUkid",warehouseUkid);
        loadData(TaskCenterConstant.URL_ADD_JOBPOINT_STEP4_PARENT_GETITEMMES, map, REQUEST_1);
    }

    /**
     * 保存步骤 第2,4,6需要这个接口
     */
    public void saveData(){
        Map<String,Object> map = new HashMap<>();
        ArrayList<TaskPointChooseRelativethingBean.ListBean> lists = new ArrayList<>();
        lists.clear();
        for(String str : listBeanMap.keySet()){
            lists.add(listBeanMap.get(str));
        }
        List<Object> categories = new LinkedList<>();
        Map<String,Object> categoriesMap;
        for(TaskPointChooseRelativethingBean.ListBean bean : lists){
            categoriesMap = new HashMap<>();
            categoriesMap.put("name","" + bean.getCategoryName());
            categoriesMap.put("ukid",bean.getMetaCategoryUkid());
            categories.add(categoriesMap);
        }

        map.put("categories",categories);
        map.put("jobPointUkid",jobPointUkid);
        map.put("type","PARENT_CATEGORY");
        NoHttpUtils.httpPost(TaskCenterConstant.URL_ADD_JOBPOINT_STEP4_PARENT_SAVEITEMMES,map,myOnresponse,REQUEST_CODE);
        showProgressDialog();
    }

    NoHttpUtils.OnResponseListener myOnresponse = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int i) {
            if("0".equals(commonClass.getCode())){
                TaskPointCardEvent taskPointCardEvent = new TaskPointCardEvent();
                taskPointCardEvent.setFinish4(true);
                EventBus.getDefault().post(taskPointCardEvent);
                popFragment();
            }else{
                toast("" + commonClass.getMsg());
            }
        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };

    @Override
    public void onClick(View v) {
        if (v == mBtSave) {
            DialogTools.getInstance().showCustomDialogPrompt(mActivity, "提示", "确认保存所选关联生产物吗？", false, new DialogTools.ConfirmListener() {
                @Override
                public void setConfirmListener(Dialog dialog, View view, String s) {
                    //确定
                    if(listBeanMap.isEmpty()){

                    }else{
                        saveData();
                    }
                    dialog.dismiss();
                }
            }, "保存", "取消");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(TaskPointChooseRelativethingBean.ListBean bean) {

        if(listBeanMap.containsKey("" + bean.getMetaCategoryUkid())){ // 含有就删除 不含有添加
//            listBeanMap.remove(listBeanMap.get("" + bean.getMetaCategoryUkid()));
            Iterator<Map.Entry<String, TaskPointChooseRelativethingBean.ListBean>> iterator = listBeanMap.entrySet().iterator();
            while (iterator.hasNext()){
                if((bean.getMetaCategoryUkid()+"").equals(iterator.next().getKey())){
                    iterator.remove();
                }
            }

        }else{
            listBeanMap.put(""+ bean.getMetaCategoryUkid(),bean);
        }
    }

}
